﻿using System;
using System.Data.SQLite;
using System.Windows;
using Microsoft.Win32;

namespace SQLiteWeldroid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string databasePath = string.Empty;
        private int seamCount = 1;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void openDbButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "SQLite Database Files|*.db";
            if (openFileDialog.ShowDialog() == true)
            {
                dbPathTextBox.Text = openFileDialog.FileName;
                databasePath = openFileDialog.FileName;
            }
        }

        private void calculateButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(databasePath))
            {
                MessageBox.Show("请先导入数据库文件。");
                return;
            }

            try
            {
                var results = GetDatabaseStatistics(databasePath);
                if (!results.Equals(null))
                {
                    weldCountText.Text = $"焊接个数: {results.WeldCount}\t\t焊接时长: {FormatTime(results.WeldDuration)}";
                    scanCountText.Text = $"扫描个数: {results.ScanCount}\t\t扫描时长: {FormatTime(results.ScanDuration)}";
                    transitionCountText.Text = $"过渡个数: {results.TransitionCount}\t\t过渡时长: {FormatTime(results.TransitionDuration)}";
                   
                    totalCountText.Text = $"总数: {results.AllCount}\t\t总时间: {FormatTime(results.TotalDuration)}";

                    // 统计 SEAMID 的不同值数量
                    int distinctSeamIdCount = GetDistinctSeamIdCount(databasePath);
                    seamCount = distinctSeamIdCount;
                    int seamsCntALL = spValue.Value;
                    double kedalv = seamCount * 100.0 / seamsCntALL;
                    kedalv = Math.Round(kedalv, 2);
                    efficiencyText.Text = $"总计焊缝:{seamCount} \t 焊接效率: {results.Efficiency} %   \t 可达率:{kedalv} %";
                    // MessageBox.Show($"DATA 表中 SEAMID 有 {distinctSeamIdCount} 种不同的值。");
                }
            }
            catch (SQLiteException ex)
            {
                MessageBox.Show($"数据库操作错误：{ex.Message}");
            }
        }

        private (int AllCount, int WeldCount, int ScanCount, int TransitionCount, double WeldDuration, double ScanDuration, double TransitionDuration, double Efficiency, double TotalDuration) GetDatabaseStatistics(string dbPath)
        {
            using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};Version=3;"))
            {
                connection.Open();

                // 查询总数
                string allQuery = "SELECT COUNT(*) FROM DATA";
                SQLiteCommand allCommand = new SQLiteCommand(allQuery, connection);
                int allCount = Convert.ToInt32(allCommand.ExecuteScalar());

                // 查询焊接个数
                string weldQuery = "SELECT COUNT(*) FROM DATA WHERE STATE IN (2, 4)";
                SQLiteCommand weldCommand = new SQLiteCommand(weldQuery, connection);
                int weldCount = Convert.ToInt32(weldCommand.ExecuteScalar());

                // 查询扫描个数
                string scanQuery = "SELECT COUNT(*) FROM DATA WHERE STATE = 1";
                SQLiteCommand scanCommand = new SQLiteCommand(scanQuery, connection);
                int scanCount = Convert.ToInt32(scanCommand.ExecuteScalar());

                // 查询过渡个数
                string transitionQuery = "SELECT COUNT(*) FROM DATA WHERE STATE = 3";
                SQLiteCommand transitionCommand = new SQLiteCommand(transitionQuery, connection);
                int transitionCount = Convert.ToInt32(transitionCommand.ExecuteScalar());

                double weldDuration = weldCount * 0.048;
                double scanDuration = scanCount * 0.048;
                double transitionDuration = transitionCount * 0.048;

                double efficiency = allCount > 0 ? (weldCount * 100.0 / allCount) : 0;
                efficiency = Math.Round(efficiency, 2);

                return (allCount, weldCount, scanCount, transitionCount, weldDuration, scanDuration, transitionDuration, efficiency, allCount * 0.048);
            }
        }

        private string FormatTime(double totalSeconds)
        {
            double minutes = Math.Floor(totalSeconds / 60);
            double seconds = totalSeconds % 60;
            return $"{minutes} 分 {seconds:0.00} 秒";
        }

        private int GetDistinctSeamIdCount(string dbPath)
        {
            using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};Version=3;"))
            {
                connection.Open();
                string distinctQuery = "SELECT COUNT(DISTINCT SEAMID) FROM DATA";
                SQLiteCommand distinctCommand = new SQLiteCommand(distinctQuery, connection);
                return Convert.ToInt32(distinctCommand.ExecuteScalar());
            }
        }
    }
}